var express = require('express');
var router = express.Router();
const db=require('../db/db');
var sd = require('silly-datetime');
var schedule = require('node-schedule');
var request = require('request');
var rule = new schedule.RecurrenceRule();
var times = [0,30];
rule.second = times;//秒

//数据库修改

//检查结束状态
function checkStatus(sql,s,now){
    var status=''
    for (let key in s) {
        var endtime=Date.parse(s[key].endtime);
        var starttime=Date.parse(s[key].starttime)
        if(now>endtime){
            status='end'
            db.query(sql,[status,s[key].id],function (err,r) {
                if (err) {
                    console.log(err);
                    return;
                } else {
                //    结束
                }
            })
        }else if (now<endtime && now>starttime){
            status='ing'
            db.query(sql,[status,s[key].id],function (err,r) {
                if (err) {
                    console.log(err);
                    return;
                } else {

                }
            })
        }

    }
}

//访问接口
router.post('/time', function(req, res, next) {
    var now=Date.parse(new Date());
    let p= () => {}
    let sql=`select * from auction`;
    db.query(sql,function (err,result) {
        if(err){
            console.log(err);
            res.send({flag:false,msg:'获取失败'});
            return;
        }else{
            var s=result
            sql=`update auction set status=? where id=?`
            p = new Promise((resolve, reject) =>{
                checkStatus(sql,s,now)
                setTimeout(() => {

                }, 100);
            });
            p.then((res) => {

            })
        }
    })
});

// 定时器
// var monitors = schedule.scheduleJob(rule, function () {
// //执行定时调用接口任务
//     request.post(
//         {
//             url: 'http://localhost:3000/auction/time',
//             },
//         function (error, response, body) {
//             if (error){
//                 console.log(error)
//             }
//             if (response.statusCode != undefined){
//             if (response.statusCode == 200) {
//                 console.log("send BothWechat message success！");
//             }
//             }
//         }
//     );
// });

module.exports = router;